﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Common.EFQuery;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApp.Web.Core;
using WebApp.Common.Caching;

namespace Infineon.UP.WebApp.Controllers
{
    public class MemberController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region CheckValidateCode

        /// <summary>
        /// 验证码验证
        /// </summary>
        /// <param name="ValidateCode"></param>
        /// <returns></returns>
        [HttpPost]
        public string CheckValidateCode(string ValidateCode)
        {
            return Utils.NvStr(ValidateCode).Trim().Equals(Utils.NvStr(Session["ValidateCode"]), StringComparison.OrdinalIgnoreCase) ? "yes" : "no";
        }

        #endregion

        #region 用户登录

        [HttpGet]
        public ActionResult Login()
        {
            var cookie = Request.Cookies.Get("User");
            if (cookie != null
                && cookie.Values["Language"] != null
                && ("zh_cn".Equals(cookie.Values["Language"]) || "zh_hk".Equals(cookie.Values["Language"])))
            {
                SessionManage.Language = cookie.Values["Language"];
            }
            else
            {
                SessionManage.Language = "zh_cn";
            }

            UserLoginModel model = new UserLoginModel();

            if (Request.Cookies["ClientID"] != null)
            {
                model.Clientid = Request.Cookies["ClientID"].Value;
            }
            if (string.IsNullOrEmpty(model.Clientid))
            {
                model.Clientid = Guid.NewGuid().ToString().Replace("-", "") + DateTime.Now.ToString("yyyyMMddHHmmss");
                Response.Cookies.Add(new HttpCookie("ClientID", model.Clientid));
            }

            model.Errornum = new S_user_loginerrorService().getErrorNumber(model.Clientid);
            model.Isneedcode = model.Errornum > 0 ? "1" : "0";

            return View(model);
        }

        [HttpPost]
        public ActionResult Login(UserLoginModel loginModel)
        {
            string urlAddress = Request.Url.ToString();
            var errlogservice = new S_user_loginerrorService();

            loginModel.Errornum = errlogservice.getErrorNumber(loginModel.Clientid);
            //loginModel.Isneedcode = loginModel.Errornum > 0 ? "1" : "0";
            loginModel.Isneedcode = "0";
            loginModel.Errorlist = new List<string>();

            //登陆信息验证            
            ViewBag.msgcode = "";
            if (string.IsNullOrEmpty(loginModel.Username))
            {
                //loginModel.Errorlist.Add("请输入用户名！");
                loginModel.Errorlist.Add(CSMSLang.Get("message_please_enter_username"));
            }

            if (string.IsNullOrEmpty(loginModel.Password))
            {
                //loginModel.Errorlist.Add("请输入用户密码！");
                loginModel.Errorlist.Add(CSMSLang.Get("message_please_enter_password"));
            }
            if (loginModel.Isneedcode == "1")
            {
                if (string.IsNullOrEmpty(loginModel.ValidateCode))
                {
                    //loginModel.Errorlist.Add("请输入验证码！");
                    loginModel.Errorlist.Add(CSMSLang.Get("message_please_enter_validatecode"));
                }
                else if (!loginModel.ValidateCode.Trim().Equals(Utils.NvStr(Session["ValidateCode"]), StringComparison.OrdinalIgnoreCase))
                {
                    //loginModel.Errorlist.Add("验证码不正确！");
                    loginModel.Errorlist.Add(CSMSLang.Get("message_validatecode_error"));
                }
            }

            if (loginModel.Errorlist.Count > 0)
            {
                loginModel.Password = "";
                loginModel.ValidateCode = "";
                return View(loginModel);
            }

            //登录处理
            S_user user = null;
            var result = UserAuthBLL.DoLogin(loginModel, loginModel.Clientid, urlAddress, ref user);

            if (result == UserLoginResults.Successful)
            {
                HttpCookie usercookie = new System.Web.HttpCookie("User");
                usercookie.Expires = DateTime.Now.AddMonths(1);
                //记录用户名Cookie
                usercookie.Values.Add("Username", loginModel.Username);
                Response.Cookies.Add(usercookie);
                //登录成功
                var backurl = Request.QueryString["backurl"];
                if (string.IsNullOrEmpty(backurl))
                {
                    return Redirect(Url.Action("Index", "Admin"));
                }
                else
                {
                    return Redirect(backurl);
                }
            }
            else
            {
                loginModel.Password = "";
                loginModel.ValidateCode = "";
                //用户名不存在，直接返回错误
                return View(loginModel);
            }
        }

        [HttpGet]
        public ActionResult Logincheck()
        {
            return View();
        }

        [HttpPost]
        [IgnoreAuthorizeFilter]
        public JsonResult Relogin()
        {
            var userid = SessionManage.User.Id;

            var result = UserAuthBLL.Relogin(userid);

            if (result == UserLoginResults.Successful)
            {
                return Json(new AjaxResult(AjaxResult.RESULT_OK, ""));
            }
            else
            {
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, CSMSLang.Get("message_login_failed")));
            }
        }

        #endregion

        #region 重复登录验证（session持续化）

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">用户ID</param>
        [IgnoreAuthorizeFilter]
        public string KeepSession(int id)
        {
            return "";
            //S_userService userservice = new S_userService();

            //SessionUserModel sessionuser = SessionManage.User;
            //if (sessionuser == null)
            //{
            //    sessionuser = new SessionUserModel(new S_userService().Find(id));
            //}

            ////验证重复登录
            //var allowmultilogin = Utils.NvBool(ConfigurationManager.AppSettings["member.allowmultilogin"]);

            //if (string.IsNullOrEmpty(SessionManage.ClientID))
            //{
            //    //Session过期
            //    return "";
            //}

            //if (!allowmultilogin)
            //{
            //    if (!userservice.CheckUserClientID(id, SessionManage.ClientID))
            //    {
            //        return GlobalConst.USER_RELOGIN;
            //    }
            //    else
            //    {
            //        SessionManage.User = sessionuser;
            //        SessionManage.ClientID = sessionuser.Clientid;
            //        return "";
            //    }
            //}
            //else
            //{
            //    return "";
            //}
        }

        #endregion
        
        #region 密码验证

        //密码长度验证
        public string PwdLengthChk(string password)
        {
            return CommonStr.CheckPasswordRule(password) == "ok" ? "yes" : "no";
        }

        #endregion

        #region Logout

        public ActionResult Logout()
        {
            UserAuthBLL.DoLogout();

            return RedirectToAction("Login", "Member");
        }

        #endregion

        #region 获取验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateVerifyCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        #endregion
        
    }
}